package com.zx.filter;/**
 * Author:JasonZ
 * Data:2023/4/17
 */

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @program: ecommerce-parent
 * @description:局部注册过滤器
 * @author: JasonZ
 * @create: 2023-04-17 14:31
 **/

public class HeadTokenGatewayFilter implements GatewayFilter {
    /**
     * Filter    void doFilter(HttpServletRequest request, response, chain)
     * OnceperRequestFilter springBoot  void doFilterInternal(HttpServletRequest request, response, chain)
     */

    // ServerWebExchange---> WebFlux api   ServletApi
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3.获取请求当中的第一个token
        String token = request.getHeaders().getFirst("token");
        System.out.println("------"+token);
        //模拟校验token
        if (!"softeem".equalsIgnoreCase(token)) {
            //设置响应码为401 即未通过认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置请求结束 返回响应
            return response.setComplete();
        }
        //通过凭证校验 继续向下传递请求
        return chain.filter(exchange);
    }
}
